package cn.spring.cloud.activity.mybatisps.springbootrabbitmq.service.impl;

import cn.spring.cloud.activity.mybatisps.springbootrabbitmq.entity.User;
import cn.spring.cloud.activity.mybatisps.springbootrabbitmq.mapper.UserMapper;
import cn.spring.cloud.activity.mybatisps.springbootrabbitmq.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2024-03-22 13:18:51
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Value("${spring.redis.key.mobile}")
    private String verifyCodeKey;

    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 通过ID查询单条数据
     *
     * @param uid 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer uid) {
        return this.userMapper.queryById(uid);
    }

    /**
     * 分页查询
     *
     * @param user        筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        this.userMapper.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userMapper.update(user);
        return this.queryById(user.getUid());
    }

    /**
     * 通过主键删除数据
     *
     * @param uid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer uid) {
        return this.userMapper.deleteById(uid) > 0;
    }

    /**
     *发送短信
     */
    public void sendMobileMessage(String mobile) {
        //生成六位随机数
        String verifyCode = RandomStringUtils.randomNumeric(6);
        //写入redis缓存
        redisTemplate.opsForValue().set(verifyCodeKey + mobile, verifyCode, 5, TimeUnit.MINUTES);
        //发给用户
        Map<String, String> stringMap = new HashMap<>();
        stringMap.put("mobile", mobile);
        stringMap.put("verifyCode", verifyCode);
        //使用了direct模式
        rabbitTemplate.convertAndSend("RabbitConstant.MOBILE_ROUTING_KEY", stringMap);
        //记录到日志中
    }





}
